package springboot.example.springboot.MultithReading;
/**
 * 多线程线程内数据一致
 */

import java.util.Random;

public class MulishReading {
    private static int num = 0;
    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                MyData.getInstance().setNum(new Random().nextInt(100));
                new A().getNum();
                new B().getNum();

            }).start();
        }
    }

    static class A {
        public void getNum() {
            System.out.println(Thread.currentThread().getName()+"A+num="+MyData.getInstance().getNum());
        }
    }

    static class B {
        public void getNum() {
            System.out.println(Thread.currentThread().getName()+"B+num="+MyData.getInstance().getNum());
        }
    }

    static class MyData{
        private static ThreadLocal<MyData> threadLocal = new ThreadLocal() ;

        static MyData getInstance(){
            MyData myData = threadLocal.get();
            if(myData == null){
                threadLocal.set(new MyData());
            }
            return threadLocal.get();
        }

        private int num;

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }
    }
}

